package com.fiveup.core.management.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fiveup.core.management.common.exception.BizException;
import com.fiveup.core.management.listener.StuUploadExcelListener;
import com.fiveup.core.management.mapper.ClazzMapper;
import com.fiveup.core.management.mapper.StuMapper;
import com.fiveup.core.management.model.DTO.BasicStudent;
import com.fiveup.core.management.model.DTO.ClassDTO;
import com.fiveup.core.management.model.DTO.StuDTO;
import com.fiveup.core.management.model.excel.StuDownloadExt;
import com.fiveup.core.management.model.excel.StuUploadExt;
import com.fiveup.core.management.service.StuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 尔宣赫
 * @date 2022/3/22
 */
@Slf4j
@Service
public class StuServiceImpl implements StuService {


    @Resource
    private StuMapper stuMapper;

    @Resource
    private ClazzMapper clazzMapper;


    @Override
    public PageInfo<StuDTO> getStudentListByPage(String keyword, Integer gender, Integer inclination, Long classId, Long schoolId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);


        if (!StringUtils.isEmpty(keyword)) {
            keyword = "%" + keyword + "%";
        }

        List<StuDTO> stuDTOList = stuMapper.getStudentListByCondition(keyword, gender, inclination, classId, schoolId);
        this.completeQueriedStuDTO(stuDTOList);
        PageInfo<StuDTO> pageInfo = new PageInfo<>(stuDTOList);
        return pageInfo;
    }

    @Override
    public List<StuDownloadExt> getStudentDownloadExtList(String keyword, Integer gender, Long classId, Long schoolId) {


        if (!StringUtils.isEmpty(keyword)) {
            keyword = "%" + keyword + "%";
        }

        List<StuDTO> stuDTOList = stuMapper.getStudentListByCondition(keyword, gender, null, classId, schoolId);// TODO
        this.completeQueriedStuDTO(stuDTOList);
        List<StuDownloadExt> stuDownloadExtList = new ArrayList<>();
        for (StuDTO stuDTO : stuDTOList) {
            StuDownloadExt stuDownloadExt = new StuDownloadExt();

            BeanUtils.copyProperties(stuDTO, stuDownloadExt);
            if (stuDownloadExt.getGender() != null) {
                stuDownloadExt.setGenderChineseCharacter(stuDownloadExt.getGender() == 0 ? "女" : "男");
            }
            stuDownloadExtList.add(stuDownloadExt);
        }
        return stuDownloadExtList;
    }


    /**
     * 使学生信息补齐完整(班级信息+TODO 成绩趋势)
     *
     * @param stuDTOList 学生list
     */
    private void completeQueriedStuDTO(List<StuDTO> stuDTOList) {
        if (stuDTOList == null || stuDTOList.size() == 0) {
            return;
        }
        for (int i = 0; i < stuDTOList.size(); i++) {
            StuDTO stuDTO = stuDTOList.get(i);
            Long classId = stuDTO.getClassId();
            ClassDTO classDTO = clazzMapper.selectOneById(classId);
            if (classDTO != null) {
                stuDTO.setClassName(classDTO.getClassName());
                stuDTO.setGrade(classDTO.getGrade());
            }
        }
    }

    //2.添加学生
    @Override
    public void addStudent(StuDTO stuDTO) throws BizException {
        Long classId = stuDTO.getClassId();
        System.out.println(classId);
        if (classId == null) {
            throw new BizException("classId为空");
        }
        //查找班级id
        ClassDTO classDTO = clazzMapper.selectOneById(classId);
        if (classDTO == null) {
            throw new BizException("该班级不存在!请联系管理员");
        }
        //插入数据
        stuMapper.insertOne(stuDTO);
    }

    //3.修改学生
    @Override
    public void alterStudent(StuDTO stuDTO) {
        stuMapper.updateOne(stuDTO);
    }

    //4.删除学生
    @Override
    public void deleteStudent(String studentId) {
        stuMapper.softlyDeleteById(studentId);
    }

    @Override
    public void uploadStuIntoDB(MultipartFile file) {
        InputStream is = null;
        try {
            is = file.getInputStream();
        } catch (IOException e) {
            log.error("uploadStuIntoDB || error={}", e.getMessage(), e);
            e.printStackTrace();
        }
        //1.进行读取数据，StuUploadExt，
        //2.new StuUploadExcelListener(this)这个是读取数据的策略
        //3.特别注意的是storageService这个service，我上面有注入进去 @Autowired，切记不要new会报错
        EasyExcel.read(is, StuUploadExt.class, new StuUploadExcelListener(this)).sheet().doRead();
    }

    @Override
    public void save(List<StuUploadExt> stuUploadExtList) throws RuntimeException {
        if (stuUploadExtList == null || stuUploadExtList.size() == 0) {
            return;
        }
        for (StuUploadExt stuUploadExt : stuUploadExtList) {
            StuDTO stuDTO = new StuDTO();
            BeanUtils.copyProperties(stuUploadExt, stuDTO);
            if (stuUploadExt.getGenderChineseCharacter() != null) {
                if ("男".equals(stuUploadExt.getGenderChineseCharacter().trim())) {
                    stuDTO.setGender(1);
                } else if ("女".equals(stuUploadExt.getGenderChineseCharacter().trim())) {
                    stuDTO.setGender(0);
                } else {
                    log.error("gender_errorly_recognised || error={}");
                    throw new RuntimeException("性别导入错误，请检查后重试!");
                }
            }
            stuMapper.insertOne(stuDTO);
        }
    }

    @Override
    public long selectCount(String stunum) {
        //构造条件构造器
        LambdaQueryWrapper<BasicStudent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BasicStudent::getStudentNum, stunum);
        Long count = stuMapper.selectCount(queryWrapper);
        return count;
    }


}
